/**
 * 客服消息回复
 */

// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp = require('request-promise')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

/**
 * 云函数入口函数
 * event格式：
 *  {
 *    Content: '1',
 *    CreateTime: 1574130528,
 *    FromUserName: 'oIH_q0GObYF_RAwvga4xvGoYZ_Xg',
 *    MsgId: 22536128047412600,
 *    MsgType: 'text',
 *    ToUserName: 'gh_882cff82edb9',
 *    userInfo:
 *    {
 *      appId: 'wx24c30e53473f699f',
 *      openId: 'oIH_q0GObYF_RAwvga4xvGoYZ_Xg'
 *    }
 *  }
 */
exports.main = async (event, context) => {
  // 请求青云API
  var res = await requestQingYunRobot(event)
  // 请求图灵API
  // var res = await requestTuLingRobot(event)
  console.log(res)
  
  if (res.result === 0 && res.content) {
    return await sendText(event, res.content)
  }
  if (res.results && res.results.length && res.results[0].resultType === 'text') {
    return await sendText(event, res.results[0].values.text)
  }
  return await sendText(event, '')
}

/**
 * 青云科技API
 */
async function requestQingYunRobot(event) {
  if (event.MsgType === 'image') {
    return { "result": 0, "content": "不要一言不合就发图~" }
  }
  var options = {
    uri: 'http://api.qingyunke.com/api.php',
    qs: {
      key: 'free',
      appid: 0,
      msg: event.Content
    },
    json: true
  }
  console.log(options)
  // 发送请求
  return await rp(options)
}

/**
 * 请求图灵API
 */
async function requestTuLingRobot(event) {
  var body = {
    "reqType": 0,
    "perception": {},
    "userInfo": {
      "apiKey": "48e79235ccba478f8edecf4d3ba73785",
      "userId": "526712"
    }
  }
  if (event.MsgType === 'image') {
    body.reqType = 1
    body.perception.inputImage = { url: event.PicUrl }
  } else {
    body.reqType = 0
    body.perception.inputText = { text: event.Content }
  }
  var options = {
    method: 'POST',
    uri: 'http://openapi.tuling123.com/openapi/api/v2',
    body: body,
    json: true // Automatically stringifies the body to JSON
  };
  console.log(options)
  
  // 发送请求
  return await rp(options)
}

/**
 * 回复文本消息
 */
async function sendText(event, content) {
  const { OPENID } = cloud.getWXContext()

  try {
    const result = await cloud.openapi.customerServiceMessage.send({
      touser: OPENID,
      msgtype: 'text',
      text: {
        content: content || '机器人打盹了~'
      }
    })
    return result
  } catch (err) {
    console.log(err)
    return err
  }
}

/**
 * 回复图片消息（待测试）
 * event.PicUrl
 */
async function sendImage(event) {
  const { OPENID } = cloud.getWXContext()
  console.log(event)

  // try {
  //   const result = await cloud.openapi.customerServiceMessage.send({
  //     touser: OPENID,
  //     msgtype: 'image',
  //     image: {
  //       mediaId: '' // 通过 customerServiceMessage.uploadTempMedia 上传的文件 ID，从接口需要配置权限
  //     }
  //   })
  //   return result
  // } catch (err) {
  //   console.log(err)
  //   return err
  // }
}
